/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2015年4月8日         Root.Lu
 */

package com.coocaa.x.service.litecontent.providers.apps.host;

import android.content.Context;
import android.net.Uri;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.Cache;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.litecontent.LiteContentProvider;
import com.coocaa.x.service.litecontent.LiteContentProvider.LiteContentProviderHost;
import com.coocaa.x.service.litecontent.LiteContentProvider.ResourceHandler;
import com.coocaa.x.service.litecontent.data.ResultPackage;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.AppData;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.AppUpdateBean;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.RP_Installed_Apps;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.RP_Update_Apps;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_theme.RP_Boolean;
import com.coocaa.x.service.litecontent.providers.apps.GameAppsProvider;
import com.coocaa.x.service.litecontent.providers.apps.LocalAppManager;
import com.coocaa.x.service.litecontent.providers.apps.LocalApps;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreException;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreUpdateBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class AppsHost_Com_Coocaa_App extends LiteContentProviderHost {
    private static AppsHost_Com_Coocaa_App instance = null;
    private Map<String, AppUpdateBean> updateBeanMap = new HashMap<String, AppUpdateBean>();
    private List<AppUpdateBean> iscompireCache = null;

    public static synchronized void create(Context context, LiteContentProvider provider) {
        if (instance == null)
            instance = new AppsHost_Com_Coocaa_App(context, provider);
    }

    private static final String MY_HOST = "com.coocaa.app";

    public AppsHost_Com_Coocaa_App(Context context, LiteContentProvider provider) {
        super(context, provider);
    }

    @Override
    public String myHost() {
        return MY_HOST;
    }
    
    /*
     * 排序（order）: installtime  usedtimes  nb  
     * 过滤（filter）:mine  delete autostart  game  launcherall launcherpick
     */


    // 2.1.1、已安装的应用
    private ResourceHandler installed_apps = new ResourceHandler(this, "/installed_apps") {

        private List<AppData> orderApp(String order, List<AppData> list) {
            //排序方式
            List<AppData> appList = new ArrayList<AppData>();
            if (order == null || order.equals(""))
                order = "nb";
            if (order.equals("installtime")) {
                appList = LocalApps.getInstance().orderAppByInstalledTime(list);
            } else if (order.equals("usedtimes")) {
                appList = LocalApps.getInstance().orderAppByUsedTimes(list);
            } else if (order.equals("nb")) {
                appList = LocalApps.getInstance().orderAppByNBWay(list);
            }
            return appList;
        }

        @Override
        public ResultPackage call(Uri uri) {
            String order = uri.getQueryParameter("order");
            String filter = uri.getQueryParameter("filter");
            LogUtils.d("app", "installed_apps  call  order:" + order + " filter:" + filter);
            List<AppData> list = new ArrayList<AppData>();
            List<AppData> appList = LocalAppManager.getInstance().getInstalledAppList();
            LogUtils.d("app", "installed_apps  appList size:" + appList.size());
            if (appList != null && appList.size() > 0) {
                //过滤规则
                if (filter.trim().equals("mine")) {
                    list = LocalApps.getInstance().orderAppForMine(orderApp(order, LocalApps.getInstance().filterAppList(appList)));
                } else if (filter.trim().equals("delete")) {
                    list = LocalApps.getInstance().orderAppForDelete(orderApp(order, LocalApps.getInstance().filterAppListForDelete(appList)));
                } else if (filter.trim().equals("autostart")) {
                    list = LocalApps.getInstance().orderAppForAutoStart(orderApp(order, LocalApps.getInstance().filterAppListForAutoStart(appList)));
                } else if (filter.trim().equals("game")) {
                    list = LocalApps.getInstance().orderAppForGame(orderApp(order, GameAppsProvider.getInstance().getGameList(appList)));
                } else if (filter.trim().equals("launcherall")) {
                    list = LocalApps.getInstance().orderAppForLauncherAll(orderApp(order, LocalApps.getInstance().filterAppList(appList)));
                } else if (filter.trim().equals("launcherpick")) {
                    list = LocalApps.getInstance().orderAppForLauncherPick(orderApp(order, LocalApps.getInstance().filterAppList(appList)));
                }

            }
            LogUtils.d("app", "installed_apps  list size:" + list.size());
//            List<AppData> items = new ArrayList<AppData>();
            RP_Installed_Apps rp = new RP_Installed_Apps();
            if (list != null && list.size() > 0) {
                for (AppData data : list) {
                    rp.resource.add(data);
                }
            }

            return rp;
        }
    };

    private ResourceHandler update_apps = new ResourceHandler(this, "/update_apps") {
        private List<AppUpdateBean> getUpdateApps(String action, String pkg, String needAll,String iscompire) {

            if (action != null && action.equals("web"))
                return getUpdateAppsFromWeb(iscompire);
            else
                return getUpdateAppsFromCache(pkg, needAll);
        }

        private List<AppUpdateBean> getUpdateAppsFromCache(String pkg, String needAll) {
            LogUtils.d("update", "getUpdateApps from cache ###############################pkg:" + pkg);
            List<AppUpdateBean> ret = new ArrayList<AppUpdateBean>();
            boolean singerApp = true;
            if (pkg == null || pkg.equals(""))
                singerApp = false;

            Cache<String, AppData> cache = LocalAppManager.getInstance().getListCache();
//            LogUtils.d("update", "getUpdateApps  size:" + cache.size());
            synchronized (updateBeanMap) {
                if (singerApp) {
                    if (updateBeanMap.containsKey(pkg)) {
                        LogUtils.d("update", "getUpdateApps  get from cache:" + updateBeanMap.size());
                        AppData data = cache.get(pkg);
                        AppUpdateBean dataMap = updateBeanMap.get(pkg);
                        LogUtils.d("update", "getUpdateApps  data version:" + data.info.versionCode + " dataMap version:" + dataMap.bean.version);
                        if (data.info.versionCode < Integer.parseInt(dataMap.bean.version))
                            ret.add(dataMap);
                        else {
                            updateBeanMap.remove(pkg);
                        }
                        LogUtils.d("update", "getUpdateApps updateBeanMap.size(): " + updateBeanMap.size());
                    }
                    if (needAll == null || !Boolean.parseBoolean(needAll))
                        return ret;
                }
                if (updateBeanMap != null && updateBeanMap.size() > 0) {
//                        for (String str : updateBeanMap.keySet()) {
//                            if (!cache.containsKey(str))
//                                updateBeanMap.remove(str);
//                            else
//                                ret.add(updateBeanMap.get(str));
//                        }                //概率性报ConcurrentModificationException

                    Iterator i = updateBeanMap.keySet().iterator();
                    while (i.hasNext()) {
                        String str = (String) i.next();
                        if (!cache.containsKey(str)) {
                            i.remove();
                            updateBeanMap.remove(str);
                        } else {
                            ret.add(updateBeanMap.get(str));
                        }
                    }

                    LogUtils.d("update", "getUpdateApps 123 size:" + ret.size() + " " + updateBeanMap.size());
                }
                return ret;
            }
        }

        private synchronized List<AppUpdateBean> getUpdateAppsFromWeb(String iscompire) {
            LogUtils.d("update", "getUpdateApps from web ###############################");
            List<AppUpdateBean> ret = new ArrayList<AppUpdateBean>();
            Cache<String, AppData> cache = LocalAppManager.getInstance().getListCache();
            LogUtils.d("update", "getUpdateApps  size:" + cache.size());

            List<AppData> infos = cache.values();
            List<AppStoreUpdateBean> beans = new ArrayList<AppStoreUpdateBean>();
            for (AppData info : infos) {
                AppStoreUpdateBean bean = new AppStoreUpdateBean();
                bean.packagename = info.info.pkgName;
                bean.version = String.valueOf(info.info.versionCode);
                beans.add(bean);
            }
            if (iscompire != null && iscompireCache != null)
                return iscompireCache;
            try {
                LogUtils.d("update", "getUpdateApps from web" + beans.size() + " iscompire " + iscompire);
                List<AppStoreUpdateBean> _beans = CoocaaApplication.getCoocaaWebService().getAppStoreService().getUpdateInfos(beans,iscompire);
                LogUtils.d("update", "getUpdateApps _beans size:" + _beans.size());
                if (_beans != null && _beans.size() > 0) {
                    synchronized (updateBeanMap) {
                        if (iscompire == null)
                            updateBeanMap.clear();
                        for (AppStoreUpdateBean _bean : _beans) {
                            AppUpdateBean uBean = new AppUpdateBean(_bean);
                            ret.add(uBean);
                            if (iscompire == null)
                                updateBeanMap.put(_bean.packagename, uBean);
                        }
                    }
                }
            } catch (AppStoreException e) {
                LogUtils.d("update", "getUpdateApps _beans error:");
                LogAPIForAppStore.reportInterfaceError("通过包名，版本号获取应用升级信息", Android.throwable2String(e));
            }
            if (iscompire != null)
                iscompireCache = ret;
            return ret;
        }

        @Override
        public ResultPackage call(Uri uri) {
            // TODO Auto-generated method stub
            String action = uri.getQueryParameter("action");   //获取数据的方式  缓存  web
            String pkg = uri.getQueryParameter("pkg");         //
            String needAll = uri.getQueryParameter("needall");
            String iscompire = uri.getQueryParameter("iscompire");
            LogUtils.d("update", "update_apps    call  uri:" + uri.toString());
            List<AppUpdateBean> list = getUpdateApps(action, pkg, needAll,iscompire);
            RP_Update_Apps rp = new RP_Update_Apps();
            if (list != null && list.size() > 0) {
                for (AppUpdateBean data : list) {
                    rp.resource.add(data);
                }
            }
            return rp;
        }

    };

    private ResourceHandler recovery_app = new ResourceHandler(this, "/recovery_app"){

        @Override
        public ResultPackage call(Uri uri) {
            String pkg = uri.getQueryParameter("pkg");
            RP_Boolean rp = new RP_Boolean();
            boolean noDelete = LocalApps.getInstance().isNoDeleteApp(pkg);
            LogUtils.d("recovery", "recovery_app    noDelete:" + noDelete);
            rp.resource = noDelete;
            return rp;
        }
    };

}
